package com.iaiai.tm.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * <p>
 * Title: CMDExecute.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2012-2-9 下午4:15:13
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class CMDExecute {

	public static synchronized String run(String[] cmd, String workdirectory) throws IOException {
		String result = "";
		try {
			ProcessBuilder builder = new ProcessBuilder(cmd);
			InputStream in = null;
			// 设置一个路径
			if (workdirectory != null) {
				builder.directory(new File(workdirectory));
				builder.redirectErrorStream(true);
				Process process = builder.start();
				in = process.getInputStream();
				byte[] re = new byte[1024];
				while (in.read(re) != -1)
					result = result + new String(re);
			}
			if (in != null) {
				in.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public static synchronized List<String> run1(String cmd) throws IOException {
		List<String> list = new ArrayList<String>();
		try {
			Process p=Runtime.getRuntime().exec(cmd);

			InputStream is = p.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
//			InputStreamReader isr = new InputStreamReader(is, "GBK");
			BufferedReader br = new BufferedReader(isr);
			String line = "";
			while ((line = br.readLine()) != null) {
				list.add(line);
			}
			br.close();
			isr.close();
			is.close();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return list;
	}
}
